use crate::config::jwt::create_jwt;
use actix_web::{post, web, HttpResponse, Responder};
use actix_web::web::Json;
use crate::config::api::R;

pub fn init(cfg: &mut web::ServiceConfig) {
    cfg.service(login);
}

#[post("/login")]
async fn login(data:String) -> impl Responder {
    let value = serde_json::from_str::<serde_json::Value>(&data).unwrap();
    let name = value.get("name").unwrap().as_str().unwrap();
    let password = value.get("password").unwrap().as_str().unwrap();
    if "admin" == name && "123456" == password {
        log::info!("login success");
    } else {
        let res: Json<R<String>> = Json(R::error(400, &String::from("账号密码错误")));
        return HttpResponse::Ok().json(res);
    }
    match create_jwt(&name) {
        Ok(jwt) =>{
            let res: Json<R<String>> = Json(R::ok(jwt));
            HttpResponse::Ok().json(res)
        } ,
        Err(e) => {
            log::error!("{}", e);
            HttpResponse::InternalServerError().body(e.to_string())
        }
    }
}
